package com.echo.im.client.handler.message;

import com.echo.im.client.helper.OnlineStatusHelper;
import com.echo.im.common.enums.IMCmdType;
import com.echo.im.common.model.*;
import com.echo.im.common.vo.message.GroupMessageVO;
import com.echo.im.common.vo.message.MessageVo;
import com.echo.im.common.vo.message.PrivateMessageVO;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author echo
 * @date 2024-08-15
 */
public abstract class AbstractMessageHandler<T extends BaseMessage<V>, V extends MessageVo> implements MessageHandler<T> {

    private final String appName;
    protected final OnlineStatusHelper onlineStatusHelper;

    public AbstractMessageHandler(OnlineStatusHelper onlineStatusHelper, String appName) {
        this.appName = appName;
        this.onlineStatusHelper = onlineStatusHelper;
    }

    public IMRecvInfo<V> createRecvInfo(T message, List<Integer> terminalList) {
        IMRecvInfo<V> recvInfo = new IMRecvInfo<>();
        recvInfo.setCmd(getCmdType(message.getData()));
        recvInfo.setSendResult(message.getSendResult());
        recvInfo.setServiceName(appName);
        recvInfo.setSender(message.getSender());
        List<IMUserInfo> userInfos = new ArrayList<>();
        for (Integer terminal : terminalList) {
            userInfos.add(new IMUserInfo(message.getSender().getId(), terminal));
        }
        recvInfo.setReceivers(userInfos);
        recvInfo.setData(message.getData());
        return recvInfo;
    }

    public IMRecvInfo<V> createRecvInfoForSelf(T message, List<Integer> terminalList) {
        IMRecvInfo<V> recvInfo = new IMRecvInfo<>();
        recvInfo.setSendResult(false);
        recvInfo.setCmd(getCmdType(message.getData()));
        recvInfo.setSender(message.getSender());
        recvInfo.setData(message.getData());

        // Create a list to hold IMUserInfo for each terminal
        List<IMUserInfo> userInfos = new ArrayList<>();
        for (Integer terminal : terminalList) {
            userInfos.add(new IMUserInfo(message.getSender().getId(), terminal));
        }
        recvInfo.setReceivers(userInfos);

        return recvInfo;
    }

    private int getCmdType(V data) {
        if (data instanceof PrivateMessageVO) {
            return IMCmdType.PRIVATE_MESSAGE.code();
        } else if (data instanceof GroupMessageVO) {
            return IMCmdType.GROUP_MESSAGE.code();
        } else {
            return IMCmdType.SYSTEM_MESSAGE.code();
        }
    }

}
